extern "C" {
#include <strings.h>
}
#include "utils.hpp"
#include "mime_type.h"

struct ext_mime_pair {
  const char* mime;
  const char* const exts[5]; // うーん...
};
static const ext_mime_pair MIME_HTML = {"text/html",       {"html", "htm", NULL}};
static const ext_mime_pair MIME_CSS  = {"text/css",        {"css", NULL}};
static const ext_mime_pair MIME_JS   = {"text/javascript", {"js", NULL}};
static const ext_mime_pair MIME_PNG  = {"image/png",       {"png", NULL}};
static const ext_mime_pair MIME_GIF  = {"image/gif",       {"gif", NULL}};
static const ext_mime_pair MIME_JPEG = {"image/jpeg",      {"jpeg", "jpg", NULL}};
static const ext_mime_pair* MIME_PAIRs[] = {
  &MIME_HTML, &MIME_CSS, &MIME_JS, &MIME_PNG, &MIME_GIF, &MIME_JPEG, NULL};
static const ext_mime_pair MIME_OCTET = {"application/octet-stream", {NULL}};

const char* get_mime_type(const char* path) {
  const char* ext = util::get_ext(path);
  if (ext == NULL) {
    return MIME_OCTET.mime;
  }
  const ext_mime_pair* pair = NULL;
  for (int i=0; (pair = MIME_PAIRs[i]) != NULL; ++i) {
    for (int k=0; pair->exts[k]!=NULL; ++k) {
      if (strcasecmp(pair->exts[k], ext) == 0) {
        return pair->mime;
      }
    }
  }
  return MIME_OCTET.mime;
}

// XXX だめだめ
const char* get_charset_str(const std::string& content_type) {
  if (content_type.find("text/") != std::string::npos) {
    return "charset=utf-8";  // TODO charset
  }
  return "";
}
